<?php

namespace App\Listeners;

use App\Events\SmsEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use App\Models\Notice\NoticeTemplate;
use App\Models\Notice\SmsRecord;
use App\Models\Account\User;
use Sms;
use Illuminate\Support\Facades\Config;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class SendSms
{

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  Event  $event
     * @return void
     */
    public function handle(SmsEvent $event)
    {
        $noticeTemplate = NoticeTemplate::where('template_id', $event->templateId)->first();

        if (!$noticeTemplate) {
            return;
        }

        $templateId = $noticeTemplate->id;
        $templateContent = $noticeTemplate->content;
        //判断模板中是否存在变量
        $pattern = '/\${\w+\}/';
        preg_match_all($pattern, $templateContent, $matches);
        $templateParams = array();
        if (count($matches[0]) > 0) {
            foreach ($matches[0] as $val) {
                $templateParams[] = substr($val, 2, -1);
            }
        }

        $users = User::whereIn('id', $event->userIds)->where('is_blocked', 0)->get(['id', 'username', 'phone'])->toArray();

        $signName = [];
        $phones = [];

        $records = [];
        $templateParamJson = [];
        $templateParamsNum = count($templateParams);
        $templateParamsKey = array_values($templateParams);
        $accessSignName = Config::get('system.sms_sign_name');

        if (count($event->payload) + 1 !== $templateParamsNum) {
            return;
        }

        $templatePayload = [];

        foreach ($event->payload as $value) {
            if (mb_strlen($value, 'utf8') > 17) {
                $templatePayload[] = mb_substr($value, 0, 17, 'utf-8') . '...';
            } else {
                $templatePayload[] = $value;
            }
        }

        foreach ($users as $user) {
            $signName[] = $accessSignName;
            $phones[] = $user['phone'];

            $payload = $templatePayload;
            array_unshift($payload, $user['username']);
            $templateParamsVal = array_values($payload);
            $templateParamsValue = array_slice($templateParamsVal, 0, $templateParamsNum);
            $templateParamJson[] = array_combine($templateParamsKey, $templateParamsValue);

            $recordPayload = $event->payload;
            array_unshift($recordPayload, $user['username']);
            $recordParamsVal = array_values($recordPayload);
            $recordParamsValue = array_slice($recordParamsVal, 0, $templateParamsNum);
            $recordParam = array_combine($templateParamsKey, $recordParamsValue);

            $content = $templateContent;

            foreach ($recordParam as $key => $val) {
                $content = str_replace('${' . $key . '}', $val, $content);
            }

            $item = [];
            $item['template_id'] = $templateId;
            $item['content'] = $content;
            $item['phone'] = $user['phone'];
            $item['user_id'] = $user['id'];
            $item['task_id'] = $event->taskId;
            $item['type'] = $event->type;
            if (Auth::check()) {
                $item['data_scope'] = Auth::user()->data_scope;
            }
            $records[] = $item;
        }

        $smsPhones = json_encode($phones, JSON_UNESCAPED_UNICODE);
        $smsParams = json_encode($templateParamJson, JSON_UNESCAPED_UNICODE);
        $smsSignName = json_encode($signName, JSON_UNESCAPED_UNICODE);
        $accessKeyId = Config::get('system.sms_access_key_id');
        $accessKeySecret = Config::get('system.sms_access_key_secret');

        $result = Sms::sendBatchSms($smsPhones, $event->templateId, $smsParams, $smsSignName, $accessKeyId, $accessKeySecret);

        if ($result->Code == "OK") {
            $requestId = $result->RequestId;
            $bizId = $result->BizId;
            foreach ($records as $key => $val) {
                $records[$key]['request_id'] = $requestId;
                $records[$key]['biz_id'] = $bizId;
                $records[$key]['created_at'] = new Carbon();
                $records[$key]['updated_at'] = new Carbon();
            }
            $smsRecord = new SmsRecord();
            $result = $smsRecord->addSmsRecord($records);
        }
    }

}
